package com.feihong.txgw.http;

import com.feihong.txgw.app.App;
import com.feihong.txgw.utils.UserLoginInfo;
import com.feihong.txgw.utils.manage.RetrofitManager;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.http
 * @class describe:
 * @time 2017/9/13 11:26
 * @change
 * @chang time
 * @class describe
 */
public class RefreshToken {

    private static final String RESULT_DATA_KEY = "data";
    private static final String RESULT_TOKEN_KEY = "token";
    private static class SingletonHolder {
        public static RefreshToken instance = new RefreshToken();
    }

    public static RefreshToken getInstance() {
        return SingletonHolder.instance;
    }

    private RefreshToken(){
    }


    /**
     * post刷新token
     * @return
     */
    public synchronized boolean RetrofitRefreshTokenForPost(){

        long lastRefreshTokenTime = App.getApp().lastUpdateToken;
        long timeSpan = (System.currentTimeMillis() - App.getApp().lastUpdateToken);
        if (lastRefreshTokenTime != 0 && timeSpan < 1000 * 60 * 10) {
            return true;
        }
        return retrofitRefreshToken();
    }

    /**
     * get刷新token
     * @return
     */
    public synchronized boolean RetrofitRefreshTokenForGet(){
        long lastRefreshTokenTime = App.getApp().lastUpdateToken;
        long timeSpan = (System.currentTimeMillis() - App.getApp().lastUpdateToken);
        // 90分钟刷新
        if (lastRefreshTokenTime != 0 && timeSpan < 1000 * 60 * 90) {
            return true;
        }
        return retrofitRefreshToken();
    }

    private boolean retrofitRefreshToken(){
        String result = null;
        try {
            result = RetrofitManager.getInstance().refreshToken(new HashMap<String, String>())
                    .execute().body();
            if(result != null){
                JSONObject jsonObject = new JSONObject(result);
                JSONObject data = jsonObject.optJSONObject(RESULT_DATA_KEY);
                if(data != null){
                    String token = data.optString(RESULT_TOKEN_KEY);
                    if(token != null){
                        App.getApp().lastUpdateToken = System.currentTimeMillis();
                        UserLoginInfo.updateUserToken(token);
                        return true;
                    }
                }
            }
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
    }
}
